package com.example.elm_server_api;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Scanner;

/**
 * @author 张建平
 * @createtime 2022/7/27 上午9:47
 */
public class AuthenticationExample {

    //实例化自定义的认证管理器
    static SampleAuthenticationManager authenticationManager = new SampleAuthenticationManager();

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.println("Please User Name:");
            String username = input.nextLine();

            System.out.println("Please Password:");
            String password = input.nextLine();

            try {
                //未认证前的 Authentication 对象是 Token
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);

                Authentication authResult = authenticationManager.authenticate(authenticationToken);

                SecurityContextHolder.getContext().setAuthentication(authResult);

                System.out.println("认证成功！");
                break;

            } catch (AuthenticationException e) {
                System.err.println("认证失败！");
            }
        }
    }
}

/**
 * 认证管理器
 */
class SampleAuthenticationManager implements AuthenticationManager {

    //模拟从数据库获得的用户权限集
    static Collection<GrantedAuthority> AUTHORITIES = new ArrayList();
    static {
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
        AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    }

    /**
     * 认证
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // String principal = authentication.getPrincipal().toString();
        if(authentication.getPrincipal().equals(authentication.getCredentials())){
            // 通过身份认证后的 Authentication 填充了权限集
            UsernamePasswordAuthenticationToken authResult =
                    new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(),AUTHORITIES);
            return authResult;
        }
        throw new BadCredentialsException("密码不正确！请从新输入密码。");
    }
}